package com.ledim.widget.view;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.letv.android.young.client.R;

/**
 * Created by ccx
 *
 */
public class LoadingBar {

    private AnimationDrawable animationDrawable = null;
    private FrameLayout mDecorView;
    private View mContentView;
    private boolean mShow;
    private FrameLayout.LayoutParams mParams;

    public LoadingBar(Activity activity) {
        this(activity, false);
    }

    public LoadingBar(Activity activity, boolean isFocusable) {
        mDecorView = (FrameLayout) activity.getWindow()
                                           .getDecorView()
                                           .findViewById(android.R.id.content);
        if (mContentView == null) {
            mContentView = LayoutInflater.from(activity).inflate(R.layout.progress_view, null);
            ImageView loadingImage = (ImageView) mContentView.findViewById(R.id.progress_view);
            loadingImage.setImageResource(R.anim.loading_animation);
            animationDrawable = (AnimationDrawable) loadingImage.getDrawable();
            animationDrawable.setOneShot(false);
            mParams =
                    new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        }

    }

    public void dismiss() {
        if (animationDrawable != null) {
            animationDrawable.stop();
        }
        mShow = false;
        mDecorView.removeView(mContentView);
    }

    public boolean isShowing() {
        return mShow;
    }

    /**
     * 点击的view即可
     */
    public void show() {
        if (mShow) {
            mDecorView.removeView(mContentView);
        }
        if (animationDrawable != null) {
            if (!animationDrawable.isRunning()) {
                animationDrawable.start();
            }
        }
        mShow = true;
        mDecorView.addView(mContentView, mParams);
    }

}
